<template>
	<view class="almost-lottery" :style="{backgroundColor:'#E91616'}">
		<public-module></public-module>
		<view class="relative">
			<image src="../../static/images/bg.jpg" mode="widthFix" class="w-100 d-block"></image>

			<view class="absolute w-100 left-0 tips px-3">
				<view class="flex j-sb a-center">
					<view class="num">参与人数：1200</view>
					<view class="text flex j-center a-center bg-warning-light " @click="showRule=true">
						<u-icon name="info-circle" color="#e4662b" size="16"></u-icon>
						<view class="text-orange">活动规则</view>
					</view>
				</view>
				<view class="flex j-sb a-center mt-3">
					<view class="num">围观人数：1200</view>
					<view class="text flex j-center a-center bg-warning-light "
						@click="navigateTo('/pages/activity/prize')">
						<u-icon name="gift" color="#e4662b" size="16"></u-icon>
						<view class="text-orange">我的奖品</view>
					</view>
				</view>
			</view>

			<view class="almost-lottery__wheel" v-if="prizeList.length">
				<almost-lottery :lotterySize="lotteryConfig.lotterySize" :actionSize="lotteryConfig.actionSize"
					:ringCount="2" :duration="1" :selfRotaty="false" :imgCircled="false" :canvasCached="true"
					:prizeList="prizeList" :prize-index="prizeIndex" @reset-index="prizeIndex = -1"
					@draw-before="handleDrawBefore" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
					@finish="handleDrawFinish" />

				<view class="flex j-center flex-column a-center">
					<view class="flex j-center a-center col-11 rounded-60 py-1" style="background-color: #ffd155;"
						@click="handlePrize">
						<u-icon name="edit-pen" color="#e4662b" size="20"></u-icon>
						<view class="font-32 font-bold ml-1 text-orange">请填写领奖信息</view>
					</view>
					<view class="text-white mt-2">您还有{{freeNum}}次抽奖机会</view>
				</view>
			</view>
		</view>
		<view class="p-3">
			<view class="gift p-3 bg-opacity">
				<view class="mb-2 text-center font-38 font-bold" style="color: #f3c865;">部分奖品展示</view>
				<view v-for="(item,index) in prizeList" :key="index">
					<view class="p-2 bg-white flex j-start a-center mt-2" v-if="item.levelName==0">
						<u--image :showLoading="true" :src="item.prizeImage" width="150rpx" height="150rpx"
							:radius="4"></u--image>
						<view class="flex-1 ml-2">
							<view class="font-bold mb-1">{{$dictByKey(prize_level,item.levelName)}}</view>
							<view class="text-danger font-36 mb-1 font-bold">{{item.prizeName}}</view>
							<view class="font-22">(图片仅供参考，最终以实物为准)</view>
						</view>
					</view>

				</view>
				<view class="flex j-sb flex-wrap">
					<block v-for="(item,index) in prizeList" :key="index">
						<view class="p-2 bg-white flex j-start mt-2 col-10" v-if="item.levelName!=0">
							<u--image :showLoading="true" :src="item.prizeImage" width="100rpx" height="100rpx"
								:radius="4"></u--image>
							<view class="flex-1 ml-2">
								<view class="font-bold mb-1">{{$dictByKey(prize_level,item.levelName)}}</view>
								<view class="text-danger font-26 mb-1">{{item.prizeName}}</view>
								<view class="font-10">(图片仅供参考，最终以实物为准)</view>
							</view>
						</view>
					</block>

				</view>
			</view>
		</view>

		<view class="flex j-sb a-center watch-view px-3 ">
			<view class="item" @click="navigateTo('/pages/index/detail')">查看项目详情</view>
			<view class="item" @click="navigateTo('/pages/index/detail')">查看户型图</view>
		</view>
		<view class="px-3">
			<view class="swiper-wrap mt-3 rounded-15 hidden">
				<video class="w100 h100" src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4"
					controls object-fit="cover" poster="https://cdn.uviewui.com/uview/album/1.jpg"
					@play="playVideo"></video>
			</view>
			<view class="swiper-wrap my-3 rounded-15 hidden">
				<swiper class="swiper" circular autoplay indicator-dots>
					<swiper-item class="swiper-img">
						<image class="swiper-img" src="/static/images/bg.jpg" mode="aspectFill"></image>
					</swiper-item>
					<swiper-item class="swiper-img">
						<image class="swiper-img" src="/static/images/bg.jpg" mode="aspectFill"></image>
					</swiper-item>

				</swiper>
			</view>
			<view class="relative w-100">
				<map class="mapView" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="15"
					:show-location="true" :enable-zoom="true" :enable-scroll="true" @tap="bindOpenLoaction">
				</map>
				<view
					class="col-5 flex j-center a-center bg-white border-primary border rounded-15 absolute bottom-0 right-0 py-1">
					<image src="/static/images/daohang.png" mode="widthFix" class="svg30"></image>
					<view class="text-primary">导航</view>
				</view>
			</view>
		</view>

		<view class="fixed z-index-100 left-0 bottom-0 w-100 bg-white p-3 flex j-sb a-center">
			<view class="flex j-start a-center">
				<u--image :showLoading="true" src="https://cdn.uviewui.com/uview/album/1.jpg" width="100rpx"
					height="100rpx" :radius="4"></u--image>
				<view class="ml-2 font-bold font-36">翡翠湾</view>
			</view>
			<view class="bg-orange text-white font-32 font-bold px-4 py-2 rounded-15">预约看房</view>
		</view>

		<view @click="onPlayMusic">
			<view class="play-music play-rotate" v-if="isPlaying">
				<!-- 播放音乐 -->
				<image src="/static/images/yinle.png" mode="widthFix" class="yl"></image>
			</view>
			<view class="play-music" v-else>
				<!-- 暂停音乐 -->
				<image src="/static/images/yinle.png" mode="widthFix" class="yl"></image>
			</view>
		</view>


		<u-popup :show="showRule" mode="bottom" :round="10" @close="showRule=false" :closeable="true">
			<view class="bg-white p-3">
				<view class="font-36 font-bold text-center mb-3">活动规则</view>
				<view style="max-height: 70vh;overflow-y: auto;">
					<u-parse :content="activeInfo.content"></u-parse>
				</view>
			</view>
		</u-popup>

		<u-popup :show="showPopUpInfo" mode="center" @close="close" :round="10" :closeable="true"
			:safeAreaInsetBottom="false">
			<view class="col-21 p-3">
				<view class="text-center font-32 font-bold mb-4">领奖信息</view>
				<input class="h-80 rounded-20 bg-light-secondary mt-3 pl-2" placeholder="姓名" v-model="formData.name" />
				<input class="h-80 rounded-20 bg-light-secondary mt-3 pl-2" placeholder="电话" v-model="formData.phone" />

				<view class="text-center h-80 bg-primary text-white flex j-center a-center mt-4 rounded-20">提交</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		activityGet,
		activityPrize
	} from '@/api/active.js'
	import AlmostLottery from '@/components/almost-lottery/index.vue'
	import {
		clearCacheFile,
		clearStore
	} from '@/components/almost-lottery/almost-utils.js'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				id: '',
				activeInfo: {},
				showRule: false,
				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 200
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				lotteryBg: require('@/static/images/lottery-bg.png'),
				// 抽奖按钮图
				actionBg: require('@/static/images/action-bg.png'),

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: true,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: false,
				// 权重随机数的最大值
				prizeWeightMax: 0,
				// 权重数组
				prizeWeightArr: [],

				// 以下为业务需求有关示例数据
				// 金币余额
				goldCoin: 20,
				// 当日免费抽奖次数余额
				freeNum: 3,



				// 地图
				latitude: 31.856662082686135,
				longitude: 117.1891449627304,
				markers: [{
					id: 1234567,
					latitude: 31.856662082686135,
					longitude: 117.1891449627304,
					width: 15,
					height: 28,
				}],

				// //展示音频
				innerAudioContext: null,
				isPlaying: false,
				MusicUrl: 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3', //播放的链接

				formData: {
					name: '',
					phone: ''
				},
				showPopUpInfo: false
			}
		},
		computed: {
			isApple() {
				return uni.getSystemInfoSync().platform === 'ios'
			}
		},
		onLoad(op) {
			if (!uni.getStorageSync('token')) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
			}
			this.prizeList = [];
			if (op.id) {
				this.id = op.id;
				this.getActive();
				this.getPrizeList();
			}
			setTimeout(() => {
				// this.onPlayMusic()
			}, 2000)
		},
		onUnload() {
			uni.hideLoading()
			uni.removeStorageSync('almostLotteryPrizeList');
			uni.removeStorageSync('almostLotteryLotteryImg');
			this.innerAudioContext.pause(); // 暂停音乐
		},
		//分享
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: this.activeInfo.name,
				path: "/pages/activity/turntable?id=" + this.id,
				imageUrl: '',
				success: () => {

				}
			}
		},
		onShareTimeline() {
			return {
				title: this.activeInfo.name,
				path: "/pages/activity/turntable?id=" + this.id,
				imageUrl: '',
				success: () => {

				}

			};
		},
		methods: {
			getActive() {
				activityGet({
					id: this.id
				}).then(res => {
					this.freeNum = res.data.drawNumberDayFree;
					this.activeInfo = res.data;
				})
			},

			bindOpenLoaction() {
				uni.openLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					success: function() {
						console.log('success');
					}
				});
			},
			playVideo() {
				this.isPlaying = false;
				this.innerAudioContext.pause(); // 暂停音乐
			},
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				clearStore()
				this.prizeList = []
				this.getPrizeList()
			},
			// 通过 popup 打开
			handleCheckPopup() {
				uni.navigateTo({
					url: '/pages/popup/popup'
				})
			},
			// 获取奖品列表
			async getPrizeList() {
				this.prizeList = [];
				uni.showLoading({
					title: '奖品准备中...'
				})

				// 等待接口返回的数据进一步处理
				let res = await activityPrize({
					activityId: this.id
				})
				let data = res.data
				if (data.length) {
					this.prizeList = data
					this.prizeList.forEach((i, index) => {
						i.prizeId = index + 1;
						i.prizeWeight = i.weight;
						i.prizeStock = 10;
					})
					// this.prizeList = data
					console.log('已获取到奖品列表数据，开始绘制抽奖转盘')

					// 计算开始绘制的时间
					if (console.time) {
						console.time('绘制转盘用时')
					}

					// 如果开启了前端控制概率
					// 得出权重的最大值并生成权重数组
					if (this.onFrontend) {
						// 生成权重数组并排序取得最大值
						this.prizeWeightArr = this.prizeList.map(item => item.prizeWeight)
						let prizeWeightArrSort = [...this.prizeWeightArr]
						prizeWeightArrSort.sort((a, b) => b - a)

						// 开放自定义权重最大值，没有自定义则取权重数组中的最大值
						this.prizeWeightMax = this.prizeWeightMax > 0 ? this.prizeWeightMax : prizeWeightArrSort[0]
					}
				}

			},
			// 模拟请求 获取奖品列表 接口，
			requestApiGetPrizeList() {
				return new Promise((resolve, reject) => {
					let requestTimer = setTimeout(() => {
						clearTimeout(requestTimer)
						requestTimer = null
						// prizeStock 奖品库存
						// prizeWeight 中奖概率，数值越大中奖概率越高，权重一样时随机中奖
						resolve({
							ok: true,
							data: [{
									prizeId: 1,
									prizeName: '卡通小风扇',
									prizeStock: 10,
									prizeWeight: 200,
									prizeImage: ''
								},
								{
									prizeId: 2,
									prizeName: '锤子吹风机',
									prizeStock: 0,
									prizeWeight: 50,
									prizeImage: ''
								},
							]
						})
					}, 200)
				})
			},
			// 抽奖开始之前
			handleDrawBefore(callback) {
				console.log('抽奖开始之前')
				let flag = false

				// 还有免费数次或者剩余金币足够抽一次 || this.goldCoin >= this.goldNum
				if (this.freeNum > 0) {
					// 更新免费次数或金币余额
					if (this.freeNum > 0) {
						this.freeNum--
					}
					// else if (this.goldCoin >= this.goldNum) {
					// 	this.goldCoin -= this.goldNum
					// }

					flag = true
				} else {
					flag = false
					uni.showModal({
						title: '提示',
						content: '今日抽奖次数已用完！',
						success: (res) => {
							// 这里需要根据业务需求处理，一般情况下会引导用户前往赚取金币的页面
							console.log('金币不足', res)
						}
					})
				}

				callback(flag)
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				if (this.prizeing) return
				this.prizeing = true

				this.tryLotteryDraw()
			},
			// 尝试发起抽奖
			tryLotteryDraw() {
				console.log('旋转开始，获取中奖下标......')
				// 判断是否由前端控制概率
				if (this.onFrontend) {
					// 前端获取中奖下标
					this.localGetPrizeIndex()
				} else {
					//远程请求接口获取中奖下标
					this.remoteGetPrizeIndex()
				}
			},
			// 本地获取中奖下标
			localGetPrizeIndex() {
				console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (!this.prizeWeightMax || !this.prizeWeightArr.length) {
					console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 prizeWeight 参数似乎配置不正确###')
					return
				}
				console.log('当前权重最大值为 =>', this.prizeWeightMax)

				// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
				let randomWeight = Math.ceil(Math.random() * this.prizeWeightMax)
				console.log('本次权重随机数 =>', randomWeight)

				// 生成大于等于随机权重的数组
				let tempMaxArrs = []
				this.prizeList.forEach((item) => {
					if (item.prizeWeight >= randomWeight) {
						tempMaxArrs.push(item.prizeWeight)
					}
				})
				console.log('tempMaxArrs', tempMaxArrs)

				// 如果大于随机权重的数组有值，先对这个数组排序然后取值
				// 反之新建一个临时的包含所有权重的已排序数组，然后取值
				let tempMaxArrsLen = tempMaxArrs.length
				if (tempMaxArrsLen) {
					tempMaxArrs.sort((a, b) => a - b)
					// 取值时，如果存在多个值，分两种情况
					if (tempMaxArrsLen > 1) {
						// 检查是否存在重复的值
						let sameCount = 0
						for (let i = 0; i < tempMaxArrs.length; i++) {
							if (tempMaxArrs[i] === tempMaxArrs[0]) {
								sameCount++
							}
						}

						// 值不相等的情况下取最接近的值，也就是第1个值
						if (sameCount === 1) {
							this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
						} else {
							// 存在值相等时，随机取值，当然这里你可以自己决定是否随机取值
							let sameWeight = tempMaxArrs[0]
							let sameWeightArr = []
							let sameWeightItem = {}
							this.prizeWeightArr.forEach((item, index) => {
								if (item === sameWeight) {
									sameWeightArr.push({
										prizeWeight: item,
										index
									})
								}
							})
							console.log('sameWeightArr', sameWeightArr)
							sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)]
							console.log('sameWeightItem', sameWeightItem)
							this.prizeIndex = sameWeightItem.index
						}
					} else {
						this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
					}
				}

				console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeName)

				// 如果奖品设有库存
				if (this.onStock) {
					console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].prizeStock)
				}
			},
			// 远程请求接口获取中奖下标
			remoteGetPrizeIndex() {
				console.warn('###当前处于模拟的请求接口，并返回了中奖信息###')
				// 模拟请求接口获取中奖信息
				let stoTimer = setTimeout(() => {
					stoTimer = null

					let list = [...this.prizeList]

					// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
					let prizeId = Math.floor(Math.random() * list.length + 1)

					// 拿到后端返回的 prizeId 后，开始循环比对得出那个中奖的数据
					for (let i = 0; i < list.length; i++) {
						let item = list[i]
						if (item.prizeId === prizeId) {
							// 中奖下标
							this.prizeIndex = i
							break
						}
					}

					console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeName)

					// 如果奖品设有库存
					if (this.onStock) {
						console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].prizeStock)
					}
				}, 200)
			},
			// 本次抽奖结束
			handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑')

				// 旋转结束后，开始处理拿到结果后的逻辑
				let prizeName = this.prizeList[this.prizeIndex].prizeName
				let tipContent = ''

				if (prizeName === '谢谢参与') {
					tipContent = '很遗憾，没有中奖，请再接再厉！'
				} else {
					// 如果奖品设有库存
					if (this.onStock) {
						let prizeStock = this.prizeList[this.prizeIndex].prizeStock
						tipContent = prizeStock ? `恭喜您，获得 ${prizeName}` : `很抱歉，您来晚了，当前奖品 ${prizeName} 已无库存`
					} else {
						tipContent = `恭喜您，获得 ${prizeName} ！`
					}
				}

				uni.showModal({
					content: tipContent,
					showCancel: false,
					complete: () => {
						this.prizeing = false
					}
				})
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)

				if (res.ok) {
					// 计算结束绘制的时间
					if (console.timeEnd) {
						console.timeEnd('绘制转盘用时')
					}
				}

				let stoTimer = setTimeout(() => {
					stoTimer = null

					uni.hideLoading()
					// uni.showToast({
					// 	title: res.msg,
					// 	mask: true,
					// 	icon: 'none'
					// })
				}, 50)
			},

			// 播放音频
			onPlayMusic() {
				if (!this.innerAudioContext) {
					this.innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext.src = this.MusicUrl;
				}

				if (this.isPlaying) {
					this.innerAudioContext.pause(); // 暂停音乐
				} else {
					this.innerAudioContext.play(); // 播放音乐
				}

				// 切换音乐播放状态
				this.isPlaying = !this.isPlaying;
				// 监听音乐播放结束事件，用于在音乐播放结束时更新播放状态和按钮显示
				this.innerAudioContext.onEnded(() => {
					this.isPlaying = false;
				});
			},

			//领奖信息
			handlePrize() {
				this.showPopUpInfo = true;
				this.formData.phone = this.userInfo.phone
			},
			close() {
				this.showPopUpInfo = false;
			},
		},

	}
</script>

<style lang="scss" scoped>
	.almost-lottery {
		padding-bottom: 200rpx;
	}

	.almost-lottery__wheel {
		position: absolute;
		left: 0;
		right: 0;
		top: 33%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		text-align: center;
	}

	.tips {
		top: 10%;

		.num {
			min-width: 200rpx;
			padding: 0 20rpx;
			height: 60rpx;
			line-height: 60rpx;
			background-color: rgba(0, 0, 0, 0.5);
			border-radius: 40px;
			color: #fff;
			font-size: 24rpx;
		}

		.text {
			min-width: 200rpx;
			padding: 0 20rpx;
			height: 60rpx;
			border-radius: 10px;
			background-color: rgba(211, 174, 135, 0.2);

			.text-orange {
				margin-left: 6rpx;
				font-size: 24rpx;
			}
		}
	}

	.bg-opacity {
		background-color: rgba(0, 0, 0, 0.5);
	}

	.watch-view {
		.item {
			width: 48%;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			border-radius: 6px;
			background-color: #ffd155;
			color: #ff532d;
			font-weight: bold;
			font-size: 36rpx;
		}
	}

	.swiper-wrap {
		width: 100%;
		height: 550rpx;

		.swiper,
		.swiper-img {
			width: 100%;
			height: 100%;
		}
	}

	.mapView {
		height: 250rpx;
		width: 100%;
	}

	.play-music {
		position: fixed;
		bottom: 200rpx;
		left: 30rpx;
		z-index: 1000;
		background-color: rgba(0, 0, 0, 0.36);
		border-radius: 50%;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		overflow: hidden;

		.yl {
			width: 40rpx;
			height: 40rpx;
		}
	}

	.play-rotate {
		animation: rotate 2s linear infinite;
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}
</style>